package br.usp.icmc.biomac.server;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import AIM.Equipment;
import AIM.ImagingObservation;
import AIM.ImagingObservationCharacteristic;
import AIM.Person;
import AIM.Polyline;
import AIM.TwoDimensionSpatialCoordinate;
import br.usp.icmc.biomac.client.Web_padService;
import br.usp.icmc.biomac.shared.CSVData;
import br.usp.icmc.biomac.shared.CSVSerie;
import br.usp.icmc.biomac.shared.ImageDicom;
import br.usp.icmc.biomac.shared.ROI;
import br.usp.icmc.dilvan.aimTemplateViewer.client.aim.ImageAnnotationAIM;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class Web_padServiceImpl extends RemoteServiceServlet implements
		Web_padService {

	// private final String server = "http://biomac.icmc.usp.br:8888";
	//private final String serverProxy = "http://biomac.icmc.usp.br:8325"; // biomac usp
	private final String serverProxy = "http://rufus.stanford.edu:8325"; //stanford proxy
	private final String serverTemplate = "http://biomac.icmc.usp.br/";
	//private String serverTemplate = "http://127.0.0.1:8888/"; // just for
	// tests

	private static ArrayList<ImageDicom> IMAGES;

	@Override
	public ArrayList<ImageDicom> getImages(String serie)
			throws IllegalArgumentException {
		
		// TODO change this for get Images from the proxy
		
		if (IMAGES == null) {
			IMAGES = new ArrayList<ImageDicom>();
			for (int i = 0; i < 10; i++) {// max 86
				String tmp = Integer.toString(i + 1);
				if (i < 9)
					tmp = "0" + tmp;
				IMAGES.add(new ImageDicom(serverTemplate + "/dicom/7/I03_00"
						+ tmp, Integer.toString(i)));
			}
		}
		return IMAGES;
	}

	@Override
	public ArrayList<CSVData> getCSVData(String parameter, String value)
			throws IllegalArgumentException {
		ArrayList<CSVData> result = new ArrayList<CSVData>();
		String url;
		if (parameter == null)
			url = serverProxy + "/search/?patientName=*";
		else
			url = serverProxy + "/search/?" + parameter + "=" + value;
		try {
			URL uri = new URL(url);
			BufferedReader br = new BufferedReader(new InputStreamReader(
					uri.openStream()));
			String linha;
			// ignore the firth line
			br.readLine();
			while ((linha = br.readLine()) != null) {
				String[] array = linha.split(",");
				@SuppressWarnings("deprecation")
				CSVData data = new CSVData(array[0], array[1], array[2],
						array[3],
						new Date(Integer.parseInt(array[4].substring(0, 4)),
								Integer.parseInt(array[4].substring(4, 6)),
								Integer.parseInt(array[4].substring(6, 8))));
				data.setCSVSerie(getCSVSerie(array[0]));
				result.add(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public ArrayList<CSVSerie> getCSVSerie(String value)
			throws IllegalArgumentException {
		ArrayList<CSVSerie> result = new ArrayList<CSVSerie>();
		String url = serverProxy + "/search/?searchtype=series&studyUID="
				+ value;
		try {
			URL uri = new URL(url);
			BufferedReader br = new BufferedReader(new InputStreamReader(
					uri.openStream()));
			String linha;
			// ignore the firth line
			br.readLine();
			while ((linha = br.readLine()) != null) {
				String[] array = linha.split(",");
				result.add(new CSVSerie(array[0], array[1], array[2], array[3],
						array[4], serverProxy + "/" + array[5].trim(),
						array[6], array[7], array[8]));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public boolean insertROI(int indexImage, ROI roi) {
		/*
		if (roi instanceof Line)
			IMAGES.get(indexImage).addLine(roi.getLabel(),
					roi.getCoordinates().get(0).getX(),
					roi.getCoordinates().get(0).getY(),
					roi.getCoordinates().get(1).getX(),
					roi.getCoordinates().get(1).getY());
		if (roi instanceof Rectangle)
			IMAGES.get(indexImage).addRectangles(roi.getLabel(),
					roi.getCoordinates().get(0).getX(),
					roi.getCoordinates().get(0).getY(),
					roi.getCoordinates().get(1).getX(),
					roi.getCoordinates().get(1).getY());
		*/
		IMAGES.get(indexImage).addROI(roi);
		return true;
	}

	@Override
	public boolean removeROI(int indexImage, int indexROI) {
		IMAGES.get(indexImage).getRois().remove(indexROI);
		return true;
	}


	public boolean editROI(int indexImage, int indexROI, ROI roi) {
		IMAGES.get(indexImage).getRois().set(indexImage, roi);
		return true;
	}

	@Override
	public boolean editROI(int indexImage, int indexROI, String label) {
		IMAGES.get(indexImage).getRois().get(indexROI).setLabel(label);
		return true;
	}

	@Override
	public HashMap<String, String> getAIMContainers() {
		HashMap<String, String> map= new HashMap<String, String>();
		map.put("Test1.xml", getAIMTemplate("Test1.xml"));
		map.put("Test2.xml", getAIMTemplate("Test2.xml"));
		return map;
	}
	
	String getAIMTemplate(String container) {
		URL url;
		try {
			url = new URL(serverTemplate + container);
			BufferedReader in = new BufferedReader(
					new InputStreamReader(
							url.openStream()));

			StringBuffer buf= new StringBuffer();
			String inputLine = in.readLine();
			
			while (inputLine != null) {
	//			System.out.println(inputLine);
				buf.append(inputLine);
				buf.append("\n");
				inputLine = in.readLine();
			}
			in.close();
			return buf.toString();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	@Override
	public String saveAIM(ImageAnnotationAIM annotation) {
		//ImageAnnotation(cagridId, aimVersion, comment, dateTime, name, uniqueIdentifier, codeValue, codeMeaning, codingSchemeDesignator, codingSchemeVersion, precedentReferencedAnnotationUID);
		AIM.ImageAnnotation imageAnnotation = new AIM.ImageAnnotation(0, "AIM.1.0", "",
				"2008-04-11T15:32:15", "0022",
				"1.2.288.3.2205383238.1512.1207945935.1", "112041",
				"Target Lesion Complete Response", "DCM", null, null);

		// Person Start
		Person person = new Person();
		person.setBirthDate("2000-01-01T00:00:00");
		person.setCagridId(0);
		person.setName("1.3.6.1.4.1.9328.50.1.0022");
		person.setId("409978");
		person.setSex("M");
		imageAnnotation.addPerson(person);
		// Person End

		// GeometricShape start
		Polyline polyline = new Polyline(0, "", "", "", "", false, -1);
		TwoDimensionSpatialCoordinate spatialCoordinate_1 = new TwoDimensionSpatialCoordinate(
				0, 0, "1.3.6.1.4.1.9328.50.1.10717", 0, 143.0, 300.0);
		TwoDimensionSpatialCoordinate spatialCoordinate_2 = new TwoDimensionSpatialCoordinate(
				0, 1, "1.3.6.1.4.1.9328.50.1.10717", 0, 92.0, 326.0);
		polyline.addSpatialCoordinate(spatialCoordinate_1);
		polyline.addSpatialCoordinate(spatialCoordinate_2);
		imageAnnotation.addGeometricShape(polyline);
		// GeometricShape end

		// Equipment start
		Equipment equipment = new Equipment(0, "GE MEDICAL SYSTEMS", "", "");
		imageAnnotation.addEquipment(equipment);
		// Equipment end

		// User start
		AIM.User user = new AIM.User(0, "A", "NWU", "Referring", 3);
		imageAnnotation.addUser(user);
		// User end

		// ImagingObservation start
		ImagingObservation imagingObservation = new ImagingObservation(0,
				"REX4010", "Calcification", "RADREX", null, "", null, null, "");
		ImagingObservationCharacteristic imagingObservationCharacteristic = new ImagingObservationCharacteristic(
				0, "REX4020", "LIDC Calcification 1", "RADREX", null, "", null,
				"");
		imagingObservation
				.addImagingObservationCharacteristic(imagingObservationCharacteristic);
		imageAnnotation.addImagingObservation(imagingObservation);
		// ImagingObservation end
		// Saving
		try {
			imageAnnotation.saveXML("/Users/kleberson/AIM_v3_rv11_XMI_XML_Schemas/AIM_testes.xml", "/Users/kleberson/AIM_v3_rv11_XMI_XML_Schemas/AIM_v3_rv11_XML.xsd");
			 FileReader reader = new FileReader("/Users/kleberson/AIM_v3_rv11_XMI_XML_Schemas/AIM_testes.xml");  
			 BufferedReader leitor = new BufferedReader(reader);  
			 String mostra = "";
			 String result = "";
			 while((mostra = leitor.readLine())!=null) {  
				 //System.out.println("Linha:"+mostra);
				 result += mostra + "\n";
			 }
			 reader.close();
			System.out.println("Ok!");
			return result;
		} catch (Exception e) {
			System.out.println("Erro!");
			return null;
		}
	}
}
